package net.wenku8.reader.view.rank

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import net.wenku8.reader.api.RankApi
import net.wenku8.reader.entity.ApiResult
import net.wenku8.reader.model.book.BookPreviewInfo
import net.wenku8.reader.state.StateLogin
import net.wenku8.reader.state.StateRank
import net.wenku8.reader.view.common.BaseViewModel

class RankDetailViewModel : BaseViewModel() {

    val bookList = mutableStateListOf<BookPreviewInfo>()
    var page by mutableIntStateOf(0)

    private var lastPage = false

    fun initData(){
        page = 0
        lastPage = false
        bookList.clear()
        loadNextPage()
    }

    fun loadNextPage(){
        if (!StateLogin.status.value){
            showSnackbar("用户未登陆")
            return
        }
        if (lastPage || dataLoading.value){
            return
        }
        dataLoading.value = true;
        page++
        viewModelScope.launch(Dispatchers.IO) {
            val apiResult = RankApi.getRankDetail(StateRank.type.value, page)
            if (ApiResult.isSuccess(apiResult)){
                bookList.addAll(apiResult.data?: emptyList())
                if (apiResult.data == null || apiResult.data!!.isEmpty()){
                    lastPage = true
                }
            }else{
                showSnackbar(apiResult.message)
            }
            dataLoading.value = false
        }
    }

}